﻿using LunchListCore.Entities;
using LunchListCore.Interfaces.Agents;
using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using LunchListCore.Interfaces.Models;

namespace LunchListContext
{
    public class GuestContext : IGuestContext
    {
        protected readonly IGuestAgent GuestAgent;

        public GuestContext(IGuestAgent guestAgent)
        {
            GuestAgent = guestAgent;
        }

        public IGuest User
        {
            get
            {
                Lazy<IGuest> user = new Lazy<IGuest>(() => GuestAgent.GetOrCreateGuest(GetUserId(), GetUserName()));
                return user.Value;
            }
        }

        protected string GetUserId()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();

            if (identity == default(WindowsIdentity))
            {
                return null;
            }

            return identity.Name;
        }

        protected string GetUserName()
        {
			string toReturn = "Unknown";
	        try
	        {
				UserPrincipal currentUser = UserPrincipal.Current;
				toReturn = currentUser.DisplayName;
	        }
	        catch (Exception)
	        {
		        //FIX: Handle
	        }

			return toReturn ?? "Unknown";
        }
    }
}

